import pandas as pd
import webbrowser
from pyecharts.charts import Line
from pyecharts import options as opts

# 文件路径
file_path = "data/北京空气质量_2020到2025.xlsx"  # 修改为你本地路径
pollutants = ['PM2.5', 'PM10', 'So2', 'No2', 'Co', 'O3']
sheet_names = ['2020', '2021', '2022', '2023', '2024', '2025']

# 读取并合并所有数据
combined_data = []
for year in sheet_names:
    df = pd.read_excel(file_path, sheet_name=year)
    df['year'] = int(year)
    combined_data.append(df[['year'] + pollutants])

df_all = pd.concat(combined_data, ignore_index=True)
yearly_avg = df_all.groupby('year')[pollutants].mean().reset_index()

# 创建折线图
line = Line()
line.add_xaxis([str(y) for y in yearly_avg['year']])
for p in pollutants:
    line.add_yaxis(
        p,
        y_axis=yearly_avg[p].round(2).tolist(),
        is_smooth=True,
        label_opts=opts.LabelOpts(is_show=True, position="top")
    )

line.set_global_opts(
    # title_opts=opts.TitleOpts(title="2020-2025年 北京主要污染物年均浓度趋势"),
    tooltip_opts=opts.TooltipOpts(trigger="axis"),
    xaxis_opts=opts.AxisOpts(name="年份"),
    yaxis_opts=opts.AxisOpts(name="年均浓度"),
    toolbox_opts=opts.ToolboxOpts(),
    legend_opts=opts.LegendOpts(pos_top="5%"),
)

# 渲染图表
output_path = "pollutant_trends_2020_2025.html"
line.render(output_path)
webbrowser.open(output_path)
